# merge_sections(static-name-without-lib,a)
function(merge_sections NAME)
    set(pdir _c_${NAME})
    set(lname lib${NAME}.a)
    set(tname ${NAME}.o)
    add_custom_target(${tname} echo "Merge sections of ${NAME}"
        COMMAND mkdir -p ${pdir} && cp ${lname} ${pdir}/da
        COMMAND cd ${pdir} && ar -x da && rm -f da
        COMMAND ${CMAKE_C_COMPILER} -o ${tname} -r ${pdir}/*
        DEPENDS ${NAME}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )
endfunction(merge_sections)



# rearchive(name OBJS a.o b.o c.o)
function(rearchive NAME)
    cmake_parse_arguments(ARG "" "" "OBJS" ${ARGN})

    set(KERNELALL ${ARG_OBJS})
    list(TRANSFORM KERNELALL APPEND .o)
    set(lname lib${NAME}.a)

    add_custom_target(merged_${NAME}.o echo "merge archive ${NAME} object files"
        COMMAND ${CMAKE_C_COMPILER} -o merged_${NAME}.o -r ${KERNELALL}
        COMMAND ar -r ${lname} merged_${NAME}.o
        DEPENDS ${KERNELALL}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )

    add_custom_target(${NAME} echo "archive ${NAME}"
        COMMAND ar -r ${lname} merged_${NAME}.o
        DEPENDS merged_${NAME}.o 
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )
endfunction(rearchive)